﻿using System.Security.Claims;
using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;

namespace JWTAPI.AuthorInfo;

public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
    public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
        // 模拟从数据库验证用户名和密码
        if (context.UserName == "abennet01" &&
            context.Password == "abennet01")
        {
            // 用户自定义属性放入token令牌中。
            var userClaims = new List<Claim>();
            userClaims.Add(new Claim("uid", Guid.NewGuid().ToString("n")));//这里可以通过固定的token从数据库中对应的用户Id。
            userClaims.Add(new Claim("nick_name", "阿笨NET"));
            userClaims.Add(new Claim(JwtClaimTypes.Name, context.UserName));
            userClaims.Add(new Claim(JwtClaimTypes.Role, "admin"));
            userClaims.Add(new Claim(JwtClaimTypes.Email, "abennet@qq.com"));

            // 用户自定义响应属性
            var customResponse = new Dictionary<string, object>();
            customResponse.Add("user_property1", "用户自定义响应属性01");
            customResponse.Add("user_property2", "用户自定义响应属性01");

            var grantValidationResult = new GrantValidationResult(subject: context.UserName,
                authenticationMethod: OidcConstants.AuthenticationMethods.Password,
                claims: userClaims,
                customResponse: customResponse);

            context.Result = grantValidationResult;
        }
        else
        {
            context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
        }
        return Task.CompletedTask;
    }
}